import { Module } from 'vuex'
import { ElMessage } from 'element-plus'
import { User } from '#/store'
import { user_login, get_user_info } from '@/api/user'
import router from '@/router'
import {
  getToken,
  setToken,
  getRoles,
  setRoles,
  getName,
  setName,
  getAvatar,
  setAvatar,
  setUserInfo,
  removeUserInfo,
  setShopInfo,
  removeToken,
  removeShopInfo
} from '@/utils/auth'
import { AES } from '@/utils/aes'

const userModule: Module<User, any> = {
  namespaced: true,
  state: {
    token: getToken(),
    roles: getRoles(),
    name: getName(),
    avatar: getAvatar(),
    introduction: '',
    userInfo: {},
    shopInfo: {}
  },
  mutations: {
    SET_TOKEN: (state, token: string) => {
      state.token = token
      setToken(token)
    },
    SET_ROLES: (state, roles: string) => {
      state.roles = roles
      setRoles(roles)
    },
    SET_NAME: (state, name: string) => {
      state.name = name
      setName(name)
    },
    SET_AVATAR: (state, avatar: string) => {
      state.avatar = avatar
      setAvatar(avatar)
    },
    SET_USERINFO: (state, userInfo: any) => {
      state.userInfo = userInfo
      setUserInfo(userInfo)
    },
    SET_INTRODUCTION: (state, introduction: string) => {
      state.introduction = introduction
    },
    SET_CHECKED_SHOP_INFO: (state, info: any) => {
      state.shopInfo = info
      setShopInfo(info)
    }
  },
  actions: {
    // user login
    login({ commit }, userInfo: any) {
      const username = AES(userInfo.username.trim())
      return new Promise((resolve, reject) => {
        user_login(username, userInfo.password)
          .then((res: any) => {
            const data = res.data
            if (data.code === 0) {
              commit('SET_TOKEN', data.data.token)
              delete data.datatoken
              localStorage.setItem('userInfo', JSON.stringify(data.data))
            } else {
              ElMessage.error({
                type: 'error',
                message: '登录失败，请稍后重试！'
              })
            }
            resolve(res.data)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // user logout
    logout({ commit, state, dispatch }) {
      return new Promise((resolve, reject) => {
        localStorage.removeItem('userInfo')
        removeToken()
        removeUserInfo()
        removeShopInfo()
        localStorage.removeItem('userInfo')
        router.push('/login')
        window.location.reload()
        resolve({ message: true })
      })
    },

    // get user info
    getInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        get_user_info(state.token)
          .then((res: any) => {
            if (!res) {
              reject('Verification failed, please Login again.')
            }

            const { roles, name, avatar, introduction } = res

            // roles must be a non-empty array
            if (!roles || roles.length <= 0) {
              reject('getInfo: roles must be a non-null array!')
            }

            commit('SET_NAME', name)
            commit('SET_ROLES', roles)
            commit('SET_AVATAR', avatar)
            commit('SET_INTRODUCTION', introduction)
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    setChecKEdShopInfo({ commit }, info: any) {
      commit('SET_CHECKED_SHOP_INFO', info)
    }
  }
}

export default userModule
